package com.cabrida.livestar.main;

import java.util.ArrayList;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout.LayoutParams;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cabrida.livestar.BaseActivity;
import com.cabrida.livestar.R;
import com.cabrida.livestar.config.Global;
import com.cabrida.livestar.config.HttpHelp;
import com.cabrida.livestar.config.Urls;
import com.cabrida.livestar.model.FansLiveListData;
import com.cabrida.livestar.model.JSONParser;
import com.cabrida.livestar.pay.PayActivity;
import com.cabrida.livestar.util.HttpUtils;
import com.cabrida.livestar.util.JsonUtils;
import com.cabrida.livestar.util.L;
import com.cabrida.livestar.util.NetworkUtils;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

/**
 * 全部直播
 */
public class FansLiveListActivity extends BaseActivity {
	public static final String TAG = FansLiveListActivity.class.getSimpleName();
	private ImageView iv_back;
	private TextView tv_title;
	private GridView gridView_live;
	private FansHomePageLiveAdapter adapter;
	private ArrayList<FansLiveListData> infoList = new ArrayList<FansLiveListData>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	
	/** 点击直播列表，支付接口 */
	private void getPayMent(final FansLiveListData data) {
		final String channel = data.getL_channel().toString();
		final String price = data.getS_price().toString();
		RequestParams params = new RequestParams();
		params.put("udid", Global.U_id);
		params.put("token", Global.U_token);
		params.put("channel", channel);
		params.put("price", price);
		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.GET_PAYMENT_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "payment_response", response.toString());
						int code = JsonUtils.getInt(response, "code", -1);
						if (code == HttpHelp.Succeed) {
							popWindows(data,FansHomePageView.PAY_TYPE_0);
						} else if(code == HttpHelp.Failure){
							JSONObject data1 = JsonUtils.getJSONObject(response, "data", new JSONObject());
							String message=JsonUtils.getString(data1,"message", "");
							if ("直播已结束".equals(message)) {
								popWindows(data,FansHomePageView.PAY_TYPE_2);
								getLiveList();
							}else {
								popWindows(data,FansHomePageView.PAY_TYPE_1);
							}
						}else {
							JSONObject data = JsonUtils.getJSONObject(response, "data", new JSONObject());
							String message=JsonUtils.getString(data,"message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}
	
	/** 获取直播列表数据 */
	private void getLiveList() {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("udid", Global.U_id);
		params.put("token", Global.U_token);
		params.put("page", 1);
		params.put("amount", 20);
		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.GET_LIVE_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "getLiveList", response.toString());
						int code = JsonUtils.getInt(response, "code", -1);
						if (code == HttpHelp.Succeed) {
							JSONObject data = JsonUtils.getJSONObject(response, "data", new JSONObject());
							JSONArray list_live = JsonUtils.getJSONArray(data, "list", new JSONArray());
							infoList = JSONParser.getFansLiveList(list_live);
							adapter.setData(infoList);
							adapter.notifyDataSetChanged();
						} else {
							JSONObject data = JsonUtils.getJSONObject(response, "data", new JSONObject());
							String message=JsonUtils.getString(data,"message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}
	
	private Dialog dialogPay;
	public void popWindows(FansLiveListData data, int type) {
		showPayDialog(data, type);
	}

	private void showPayDialog(FansLiveListData data, int type) {
		initPayDialogView(data, type);
		if (null != dialogPay && dialogPay.isShowing()) {
			return;
		}
		if (null != dialogPay) {
			/**
			 * 等数据加载完毕，显示对话框
			 */
			Window window = dialogPay.getWindow();
			// 设置显示动画
			window.setWindowAnimations(R.style.main_menu_animstyle);
			WindowManager.LayoutParams wl = window.getAttributes();
			wl.x = 0;
			wl.y = ((Activity) context).getWindowManager().getDefaultDisplay()
					.getHeight();
			// 以下这两句是为了保证按钮可以水平满屏
			wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
			wl.height = ViewGroup.LayoutParams.MATCH_PARENT;
			// 设置显示位置
			dialogPay.onWindowAttributesChanged(wl);
			// 设置点击外围解散
			dialogPay.setCanceledOnTouchOutside(true);
			dialogPay.show();
		}
	}

	private void initPayDialogView(final FansLiveListData data,
			final int type) {
		LayoutInflater mInflater = LayoutInflater.from(context);
		View view = mInflater.inflate(R.layout.dialog_pay, null);
		TextView tv_text = (TextView) view.findViewById(R.id.tv_text);
		TextView tv_msg = (TextView) view.findViewById(R.id.tv_msg);
		ImageView iv_pay = (ImageView) view.findViewById(R.id.iv_pay);
		LinearLayout ll_pay_num = (LinearLayout) view.findViewById(R.id.ll_pay_num);
		LinearLayout ll_num = (LinearLayout) view.findViewById(R.id.ll_num);
		if (type == FansHomePageView.PAY_TYPE_0) {
			tv_text.setText("确认观看");
			iv_pay.setVisibility(View.VISIBLE);
			tv_msg.setVisibility(View.GONE);
		}
		if (type == FansHomePageView.PAY_TYPE_1) {
			tv_text.setText("立即购买");
			iv_pay.setVisibility(View.GONE);
			tv_msg.setVisibility(View.VISIBLE);
			tv_msg.setText("余额不足");
		}
		
		if (type == FansHomePageView.PAY_TYPE_2) {
			tv_text.setText("确定");
			ll_pay_num.setVisibility(View.GONE);
			ll_num.setVisibility(View.GONE);
			iv_pay.setVisibility(View.GONE);
			tv_msg.setVisibility(View.VISIBLE);
			tv_msg.setText("直播已结束");
		}

		ImageButton ib_close = (ImageButton) view.findViewById(R.id.ib_close);
		ib_close.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (null != dialogPay) {
					dialogPay.dismiss();
				}
			}
		});
		LinearLayout ll_sure = (LinearLayout) view.findViewById(R.id.ll_sure);
		ll_sure.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (null != dialogPay) {
					dialogPay.dismiss();
				}
				//setPayment(channel, GroupId);
				if (type == FansHomePageView.PAY_TYPE_0) {
					setPayment(data);
				}
				if (type == FansHomePageView.PAY_TYPE_1) {
					gotoPay();
				}

			}
		});

		dialogPay = new Dialog(context, R.style.dialogWindowStyle);
		dialogPay.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialogPay.setContentView(view, new LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
	}
	
	/**
	 * 进入直播
	 */
	public void setPayment(FansLiveListData data) {
		Intent intent = new Intent();
		intent.setClass(context, FansLiveRoomActivity.class);
		intent.putExtra("data", data);
		context.startActivity(intent);
	}
	
	/**
	 * 进入购买界面
	 */
	public void gotoPay() {
		Intent intent = new Intent();
		intent.setClass(context, PayActivity.class);
		context.startActivity(intent);
	}

	@Override
	protected void findViewById() {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_fans_livelist);
		iv_back = (ImageView) findViewById(R.id.iv_back);
		tv_title = (TextView) findViewById(R.id.tv_title);
		gridView_live = (GridView) findViewById(R.id.gridView_live);
	}

	@Override
	protected void initView() {
		// TODO Auto-generated method stub
		iv_back.setOnClickListener(this);
		tv_title.setText(getString(R.string.fans_homepage_live_more));
		adapter = new FansHomePageLiveAdapter(context);
		gridView_live.setAdapter(adapter);
		gridView_live.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				FansLiveListData data = (FansLiveListData) arg0.getAdapter().getItem(arg2);
				getPayMent(data);
			}
		});
		
		getLiveList();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		super.onClick(v);
		switch (v.getId()) {
		case R.id.iv_back:
			this.finish();
			break;
		default:
			break;
		}
	}

}
